package hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        /*
         *   Spring Security 5.0开始密码必须配置加密类
         *   当前版本5新增支持加密方式：
         *   bcrypt - BCryptPasswordEncoder (Also used for encoding)
         *   ldap - LdapShaPasswordEncoder
         *   MD4 - Md4PasswordEncoder
         *   MD5 - new MessageDigestPasswordEncoder("MD5")
         *   noop - NoOpPasswordEncoder   //不加密
         *   pbkdf2 - Pbkdf2PasswordEncoder
         *   scrypt - SCryptPasswordEncoder
         *   SHA-1 - new MessageDigestPasswordEncoder("SHA-1")
         *   SHA-256 - new MessageDigestPasswordEncoder("SHA-256")
         *   ha256 - StandardPasswordEncoder
         */
        PasswordEncoder noop=NoOpPasswordEncoder.getInstance();//不加密

        auth.inMemoryAuthentication()
                .withUser("guest").password("123456").roles("Guest")
                .and()
                .withUser("admin").password("123456").roles("Admin")
                .and()
                .passwordEncoder(noop);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .antMatchers("/adminPage/**").access("hasRole('Admin')")
                .antMatchers("/guestPage/**").access("hasRole('Guest') or hasRole('Admin')")
                .antMatchers("/**").permitAll()//匹配规则是先配置的先匹配，一但匹配成功，不再向下匹配。如果"/**"配置在最前面,将起不到拦截作用。
                .and().formLogin()
                .and().logout()
                .and().csrf().disable();
    }
}